﻿using System;
using System.Windows.Input;

namespace FieldTools.MediaFindOut
{
    /// <summary>
    /// 命令基类
    /// </summary>
    /// <remarks>
    /// 
    /// </remarks>
    /// <param name="execute"></param>
    /// <param name="canExecute"></param>
    public class BaseCommand(Action<object?>? execute, Func<object?, bool?>? canExecute) : ICommand
    {
        /// <inheritdoc/>
        public event EventHandler? CanExecuteChanged
        {
            add
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested += value;
                }
            }
            remove
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested -= value;
                }
            }
        }

        /// <inheritdoc/>
        public bool CanExecute(object? parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }
            return _canExecute(parameter) ?? true;
        }
        /// <inheritdoc/>
        public void Execute(object? parameter)
        {
            if (_execute != null && CanExecute(parameter))
            {
                _execute(parameter);
            }
        }

        private readonly Func<object?, bool?>? _canExecute = canExecute;
        private readonly Action<object?>? _execute = execute;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="execute"></param>
        public BaseCommand(Action<object?>? execute) :
            this(execute, null)
        {
        }
    }
}
